<template>
  <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
    <div style="margin-right: 1px">
      <a-button @click="add(-1, {})" type="primary" :disabled="isReadOnly">新增</a-button>
      <a-button @click="del" type="danger" :disabled="isReadOnly">删除</a-button>
    </div>
    <vxe-table
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      align="center"
      ref="xTable"
      max-height="280"
      border
      show-overflow
      :key="tableKey"
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
      @checkbox-all="checkboxAll"
      @checkbox-change="checkboxChange"
      :edit-rules="cusPersonItemValidRules"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" min-width="60"></vxe-column>
      <vxe-column min-width="150" field="cusPerson" title="联系人" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.cusPerson" placeholder="请输入联系人" :readonly="isReadOnly"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column min-width="160" field="cusPhone" title="联系电话" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input
            v-model="row.cusPhone"
            placeholder="请输入联系电话"
            maxlength="11"
            @keyup.native="row.cusPhone = row.cusPhone.replace(/\s+/g, '')"
            :readonly="isReadOnly"
          ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column min-width="150" field="maiorCusPerson" title="主联系人" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ fromatMaiorCusPerson(row.maiorCusPerson) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select
            :disabled="isReadOnly"
            placeholder="请选择是否为主联系人"
            v-model="row.maiorCusPerson"
            @change="handlechange(row, $event)"
            transfer>
            <vxe-option
              v-for="item in maiorCusPersonData"
              :key="item.code"
              :value="item.code"
              :label="item.name">
            </vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column min-width="300" field="remark" title="备注信息" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.remark" placeholder="请输入备注信息" :readonly="isReadOnly"></vxe-input>
        </template>
      </vxe-column>
    </vxe-table>
  </a-form-item>
</template>

<script>
import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import { mapGetters } from 'vuex'
import Sortable from 'sortablejs'
export default {
  name: 'CusPersonTableFormItem',
  props: {
    oldTableData: {
      type: Array,
      require: false,
      default() {
        return []
      }
    },
    detailReadOnly: {
      type: Boolean,
      require: false,
      default: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      tableData: [],
      isReadOnly: false,
      delDisable: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      // 组件key发生变化，则会强制对该组件进行刷新
      tableKey: 0,
      // 定义的规则变量
      cusPersonItemValidRules: {
        cusPerson: [
          { required: true, message: '联系人不能为空' }
        ],
        cusPhone: [
          { required: true, message: '手机号码不能为空' },
          { pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '手机号码格式不正确' }
        ]
      },
      maiorCusPersonData: [
          {
            name: '是',
            code: '1'
          },
          {
            name: '否',
            code: '-1'
          }
      ]
    }
  },
  created() {
    this.tableData = this.oldTableData
    this.isReadOnly = this.detailReadOnly
  },
  methods: {
    drag() {
      this.$nextTick(() => {
        Sortable.create(this.$refs.xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'),
          {
            handle: '.drag-btn',
            animation: 150,
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0]
              this.tableData.splice(newIndex, 0, currRow)
              this.tableKey++
            }
          }
        )
      })
    },
    // 新增方法
    async add(row, record) {
      // 对表格主联系人设置初始值
      let islife = false
      this.tableData.forEach(item => {
        if (item.maiorCusPerson === '1') {
          islife = true
        }
      })
      if (islife) {
        record.maiorCusPerson = '-1'
      } else {
        record.maiorCusPerson = '1'
      }
      // 表格数据进行新增
      await this.$refs.xTable.insertAt(record, row)
      const $table = this.$refs.xTable
      await this.$emit('add', $table.getTableData())
      Object.assign(this.tableData, this.$refs.xTable.getTableData().tableData)
    },
    // 删除方法
    async del() {
      // 弹出框
      const type = await VXETable.modal.confirm('您确定要删除该数据?')
      if (type === 'confirm') {
        await this.$refs.xTable.removeCheckboxRow()
      }
      const $table = this.$refs.xTable
      await this.$emit('del', $table.getTableData())
      this.tableData = this.$refs.xTable.getTableData().tableData
      this.isDisableDel()
    },
    // 删除按钮是否禁用
    isDisableDel() {
      // 如果选择的记录为零则进行
      this.delDisable = this.$refs.xTable.getCheckboxRecords().length <= 0
    },
    // 全部选中
    checkboxAll({ checked, $event }) {
      this.isDisableDel()
    },
    // 选中变化
    checkboxChange({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      this.isDisableDel()
    },
    // 清除表格内容
    clearTableData() {
      this.tableData = []
    },
    // 刷新表格
    refreshTable(val) {
      this.$refs.xTable.reloadData(val)
    },
    // 将主联系人显示从id改为名字
    fromatMaiorCusPerson(value) {
      return XEUtils.find(this.maiorCusPersonData, item => item.code === value)?.name
    },
    // 更改一个主联系人为是 其他主联系人改为否
    handlechange(row, val) {
      this.tableData.forEach(item => {
        if (item.maiorCusPerson === '1' && item._X_ROW_KEY !== row._X_ROW_KEY) {
          item.maiorCusPerson = '-1'
        }
      })
    }
  },
  watch: {
    //  监听tableData变化
    tableData: {
      handler() {
        this.$emit('tableDataChange', this.tableData)
      },
      deep: true
    },
    tableKey: {
      handler() {
        //  表格数据刷新后重新调用拖拽方法
        this.drag()
      },
      deep: true
    }
  }
}
</script>
<style scoped>
</style>
